<template>
  <div>
    <a-modal
      v-model:visible="sVisible"
      :title="title"
      cancelText="取消"
      okText="提交"
      width="60%"
      :footer="null"
      @ok="submit"
      @cancel="cancel"
    >
      <pro-table
        ref="tableRef"
        :fetch="fetch"
        :columns="defaultColumns"
        :operate="operate"
        :param="state.param"
        :pagination="pagination"
      >
      </pro-table>
    </a-modal>
  </div>
</template>

<script>
import { ref, reactive, watch, nextTick } from "vue";
import { page } from "@/api/module/school";
import { cloneDeep } from 'lodash';

export default {
  name: "university",
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    columns: {
      type: Array,
      default: () => ([])
    },
    fetchAjax: {
      type: Function,
      default: page
    },
    title: {
      type: [String, Number],
      default: '选择学校'
    },
    searchParams: {
      type: Object,
      default: () => ({})
    }
  },
  emits: ['update:visible', 'selectUniversity'],
  setup(props, content) {
    const tableRef = ref(null)
    const sVisible = ref(props.visible)
    const pagination = {
      pageNum: 1,
      pageSize: 10
    }
    const state = reactive({
      selectedRowKeys: [],
      param: {},
    })
    const defaultColumns = ref([])

    const fetch = async (params) => {
      const response = await props.fetchAjax(params)
      if (response.code === 500) {
        return {
          data: [],
          total: 0
        }
      }
      return {
        data: response.data.record,
        total: response.data.total,
      }
    }

    watch(
      () => props.visible,
      () => {
        sVisible.value = props.visible

        if (props.visible) {
          nextTick(() => {
            tableRef.value.fetch({ current: 1 })
          })
        }
      },
      { immediate: true }
    )

    watch(
      () => props.searchParams,
      () => {
        state.param = {
          ...state.param,
          ...props.searchParams
        }
      },
      { immediate: true }
    )

    watch(
      () => props.columns,
      () => {
        defaultColumns.value = cloneDeep(props.columns)
      },
      { immediate: true }
    )

    /// 行操作
    const operate = [
      {
        label: "选择",
        event: function (record) {
          content.emit('selectUniversity', record)
          content.emit('update:visible', false)
        }
      },
    ];

    const cancel = () => {
      defaultColumns.value = []
      content.emit("update:visible", false);
    }

    return {
      state,
      operate,
      sVisible,
      tableRef,
      pagination,
      fetch,
      cancel,
      defaultColumns
    }
  }
}
</script>

<style scoped>

</style>
